package net.caixiaomi.info.ui.details;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;

import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.adapter.ArticleAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.ArticleDetailModel;
import net.caixiaomi.info.model.ArticleItem;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.ShareModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.presenter.WebviewPresenter;
import net.caixiaomi.info.ui.dialog.ShareDialogFragment;
import net.caixiaomi.info.ui.mine.CollectActivity;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

public class ArticleDetailActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, View.OnClickListener {

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    @BindView(R.id.flag)
    View mFlag;

    private String mId;
    private ArticleAdapter mAdapter;
    private TextView mTitle;
    private TextView mTime;
    private WebView mWebView;
//    private MenuItem mCollectItem;
//    private MenuItem mShareItem;
    @BindView(R.id.web_ic_share)
    RelativeLayout mShareTv;
    @BindView(R.id.web_ic_collect)
    ImageView mCollectImg;

    @OnClick(R.id.web_ic_share)
    void shareClick(){
        if (mModel != null) {
            ShareModel shareModel = new ShareModel();
            shareModel.setTitle(mModel.getTitle());
            shareModel.setDescription(mModel.getSummary());
            shareModel.setUrl(mModel.getLink()+"&qd="+AppHelper.getChanel(ArticleDetailActivity.this));
//                shareModel.setThumbUrl(mModel.getArticleThumb());

            ShareDialogFragment shareDialog = new ShareDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", JSON.toJSONString(shareModel));
            shareDialog.setArguments(bundle);
            shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
//        mPresenter.goBack();
        if (getCurrentFocus() != null) {
            AppHelper.hideKeyboard(getCurrentFocus());
        }
        if(mWebView.canGoBack()){
            mWebView.goBack();
        }else{
            finish();
        }
    }

    @OnClick(R.id.web_ic_collect)
    void collectClick(){
        collectArticle();
    }

    private ArticleDetailModel mModel;
    private View mHeader1;
    private View mHeader2;
    private TextView mFooter;
    private WebviewPresenter mPresenter;

    @Override
    protected int layout() {
        return R.layout.act_article_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        mId = getIntent().getStringExtra("data");
        initView();
        loadData();

        mPresenter=new WebviewPresenter(this,mWebView, new WebviewPresenter.WebCallBack() {

            @Override
            public void changedTitle(String title) {
                changeTitle(title);
            }

            @Override
            public void hideTitle(boolean hide) {
                if(hide){
                    findViewById(R.id.toolbar).setVisibility(View.GONE);
                }else{
                    findViewById(R.id.toolbar).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void hideDelete(boolean hide) {
                if(hide){
                    findViewById(R.id.btn_close).setVisibility(View.GONE);
                }else{
                    findViewById(R.id.btn_close).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void goShare(String title, String description, String url, String thumbUrl) {
                ShareModel shareModel = new ShareModel();
                shareModel.setTitle(title);
                shareModel.setDescription(description);
                url=url+"&qd="+AppHelper.getChanel(ArticleDetailActivity.this);
                shareModel.setUrl(url);
                shareModel.setThumbUrl(thumbUrl);
                ShareDialogFragment shareDialog = new ShareDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("data", JSON.toJSONString(shareModel));
                shareDialog.setArguments(bundle);
                shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
            }
        });
    }

//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.article, menu);
//        mCollectItem = menu.findItem(R.id.btn_collect);
//        mCollectItem.setVisible(false);
//        mShareItem = menu.findItem(R.id.btn_share);
//        mShareItem.setVisible(false);
//        return true;
//    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.btn_collect:
                collectArticle();
                break;
            case R.id.btn_share:
                if (mModel == null)
                    return false;
                ShareModel shareModel = new ShareModel();
                shareModel.setTitle(mModel.getTitle());
                shareModel.setDescription(mModel.getSummary());
                shareModel.setUrl(mModel.getLink());
//                shareModel.setThumbUrl(mModel.getArticleThumb());

                ShareDialogFragment shareDialog = new ShareDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("data", JSON.toJSONString(shareModel));
                shareDialog.setArguments(bundle);
                shareDialog.show(getSupportFragmentManager(), shareDialog.getClass().getName());
                break;
        }
        return true;
    }

    private void initView() {
        mShareTv.setVisibility(View.GONE);
        mProgress.setVisibility(View.GONE);
        mLoading = new DefLoading(this);
        mListView.setVisibility(View.INVISIBLE);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mHeader1 = LayoutInflater.from(CommonApp.getInstance()).inflate(R.layout.header_article_detail, null);
        mHeader2 = LayoutInflater.from(CommonApp.getInstance()).inflate(R.layout.item_common_title, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = (int) getResources().getDimension(R.dimen.padding_8);
        mHeader2.setLayoutParams(layoutParams);
        TextView title = (TextView) mHeader2.findViewById(R.id.title);
        title.setText(R.string.C_RELATED_ARTICLE);
        mHeader2.setVisibility(View.GONE);

        mTitle = (TextView) mHeader1.findViewById(R.id.title);
        mTime = (TextView) mHeader1.findViewById(R.id.time);
        mWebView = (WebView) mHeader1.findViewById(R.id.web);

        mFooter = new TextView(this);
        mFooter.setId(R.id.btn_logout);
        layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mFooter.setLayoutParams(layoutParams);
        mFooter.setText(R.string.C_LOOK_MORE);
        mFooter.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), R.color.secondary_text));
        mFooter.setPadding(0, (int) getResources().getDimension(R.dimen.padding_12), 0, (int) getResources().getDimension(R.dimen.padding_12));
        mFooter.setGravity(Gravity.CENTER);
        mFooter.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font_14));
        mFooter.setOnClickListener(this);
        mFooter.setVisibility(View.GONE);

        initWebView();
        mAdapter = new ArticleAdapter(null);
        mAdapter.setOnItemClickListener(this);
        mAdapter.addHeaderView(mHeader1);
        mAdapter.addHeaderView(mHeader2);
        mAdapter.addFooterView(mFooter);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setHeaderFooterEmpty(false, false);
        mListView.setAdapter(mAdapter);
    }

    private void initWebView() {
        try {
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDefaultTextEncodingName("UTF-8");//设置默认为utf-8
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
            webSettings.setAllowFileAccess(true); //设置可以访问文件
            webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
            webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
            webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
            webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能
            String ua = "";
            try {
                ua=webSettings.getDefaultUserAgent(this);
                ua="app/android&"+ua;
            } catch (NoSuchMethodError e) {
            }
            webSettings.setUserAgentString(ua);
            mWebView.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                    handler.proceed();
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    startAnimator();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("articleId", mId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ArticleDetailModel>> baseCallModelCall = requestService.articleDetail(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<ArticleDetailModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<ArticleDetailModel> data) {
                mListView.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.GONE);
                ArticleDetailModel model = data.data;
                bindData(model);
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);

            }
        });
    }

    private void collectArticle() {
        if (mModel == null)
            return;
        mLoading.show();
        JSONObject params = new JSONObject();

        params.put(TextUtils.equals(mModel.getIsCollect(), "1") ? "id" : "articleId", mModel.getArticleId());

        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> baseCallModelCall = TextUtils.equals(mModel.getIsCollect(), "1") ? requestService.collectDelete(params) : requestService.collectAdd(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel>(this) {
            @Override
            public void onSuccess(BaseCallModel data) {
                if (TextUtils.equals(mModel.getIsCollect(), "1")) {
                    mModel.setIsCollect("0");
                } else {
                    mModel.setIsCollect("1");
                }
                mLoading.dismiss();
                mCollectImg.setBackgroundResource(TextUtils.equals(mModel.getIsCollect(), "1") ? R.mipmap.ic_collected : R.mipmap.ic_collect_normal_title);
//                mCollectItem.setIcon(TextUtils.equals(mModel.getIsCollect(), "1") ? R.mipmap.ic_collected : R.mipmap.ic_collect_normal);
                ToastUtil.s(data.msg);
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });
    }

    private void bindData(ArticleDetailModel model) {
        try {
            if (model == null) {
                return;
            }
            mModel = model;
            mShareTv.setVisibility(View.VISIBLE);
            mCollectImg.setVisibility(View.VISIBLE);
            mCollectImg.setBackgroundResource(TextUtils.equals(model.getIsCollect(), "1") ? R.mipmap.ic_collected : R.mipmap.ic_collect_normal_title);
//            mCollectItem.setVisible(true);
//            mShareItem.setVisible(true);
//            mCollectItem.setIcon(TextUtils.equals(model.getIsCollect(), "1") ? R.mipmap.ic_collected : R.mipmap.ic_collect_normal);
            mTitle.setText(model.getTitle());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm");
            String time = simpleDateFormat.format(new Date(Long.valueOf(model.getAddTime()) * 1000));
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(model.getAuthor()).append("   ").append(time).append("   ").append(CommonApp.getInstance().getString(R.string.C_READ)).append(!TextUtils.isEmpty(model.getClickNumber()) ? model.getClickNumber() : "");
            mTime.setText(stringBuilder);
            String text = "<html>\n" +
                    "<head>\n" +
                    "<meta charset=\"utf-8\">\n" +
                    "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no\">\n" +
                    "<style>\n" +
                    " img{max-width: 100%; width:auto; height:auto;}\n" +
                    "</style>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    model.getContent() +
                    "</body>\n" +
                    "</html>";
            mWebView.loadData(text, "text/html; charset=UTF-8", null);
            mAdapter.getData().clear();
            List<ArticleItem> articles = model.getArticles();
            mHeader2.setVisibility(articles.isEmpty() ? View.GONE : View.VISIBLE);
            mFooter.setVisibility(articles.isEmpty() ? View.GONE : View.VISIBLE);

            mAdapter.addData(articles);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_LOGIN:
                    collectArticle();
                    break;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            ArticleItem item = (ArticleItem) adapter.getData().get(position);
            Intent intent = new Intent(this, ArticleDetailActivity.class);
            intent.putExtra("data", item.getArticleId());
            startActivity(intent);
            onBackPressed();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, CollectActivity.class);
        intent.putExtra("data", mId);
        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mId = intent.getStringExtra("data");
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "zixun-view");

    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "zixun-view");
    }

    private void startAnimator() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mFlag, "alpha", 1f, 0f);
        animator.setDuration(500);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mFlag.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();

    }


}
